//
//  HRTimeLineViewController.m
//  SpeedDating
//
//  Created by ISU1 on 17/2/10.
//  Copyright © 2017年 isu. All rights reserved.
//

#import "FriendLineViewController.h"
#import "MessageModelManager.h"
#import "SDTimeLineTableHeaderView.h"
#import "SDTimeLineCell.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "SDTimeLineCellModel.h"
#import <AVFoundation/AVFoundation.h>
//个人信息
#import "HomeStrangCollionViewController.h"
#import "HRTextMessage.h"
//发状态
#import "FrienddynamicViewController.h"
#import "Friendconversations.h"
//发布状态弹框
#import "GGActionSheet.h"
//朋友圈新回复消息
#import "FriendlinNewMessageViewController.h"
#import "UIButton+WebCache.h"
#define kTimeLineTableViewCellId @"SDTimeLineCell"

@interface FriendLineViewController ()<UITableViewDelegate, UITableViewDataSource,SDTimeLineCellDelegate,RCChatSessionInputBarControlDelegate, RCEmojiViewDelegate, UITextViewDelegate,UIImagePickerControllerDelegate, CAAnimationDelegate,FrienddynamicViewControllerDelegate,UINavigationControllerDelegate,FriendconversationsDelegate,GGActionSheetDelegate>


@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, retain) RCChatSessionInputBarControl *chetctr;

@property (nonatomic, assign) CGFloat y;

@property (nonatomic, assign) NSInteger circleId;

@property (nonatomic, assign) NSInteger trystId;

@property (nonatomic, strong) NSIndexPath *selectIndexPath;

@property (nonatomic, strong)SDTimeLineTableHeaderView *headerView;

@property (nonatomic, strong)UserpersionlInfoModel *userInfoModel;

//回复
@property (nonatomic, copy  ) NSString *commentToUser;
@property (nonatomic, strong) UILabel *labCommentId;
@property (nonatomic, strong) NSString *CommentIdStr;
@property (nonatomic, strong) NSString *CommentStrList;
@property (nonatomic, strong) NSString *CommentUserId;
@property (nonatomic, strong) NSString *CommentKeybord;

//播放视频
@property (nonatomic, strong) AVPlayer *player ;
@property (nonatomic, strong) AVPlayerLayer *playerLayer ;
@property (nonatomic, strong) UIView *PlayerView;
//弹框
@property (nonatomic, strong) GGActionSheet *actionSheetTitle;
@property (nonatomic, assign) CGRect keyboardR;
//最新消息个数
@property (nonatomic, strong) NSDictionary *FriendmessageCount;
@property (nonatomic, strong) UIView *messageView;
@property (nonatomic, strong) UIImageView *messagePhoto;
@property (nonatomic, strong) UILabel *messageCount;


@end

@implementation FriendLineViewController {
    
    NSInteger page;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
 
    
    self.view.backgroundColor = RGB(222, 222, 222);
    [self.navigationItem setTitle:@"朋友圈"];
    if (_herId.length == 0) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Friend_news_camera"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(clickRightButton)];
    }

    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
            make.top.equalTo(self.view).offset(0);
        }];
    }
    self.chetctr.hidden = YES;
    page = 1;
    
    _headerView = [SDTimeLineTableHeaderView new];
    _headerView.frame = CGRectMake(0, 0, 0, 300);
    

    
    
    self.messageView= [[UIView alloc] init];
    self.messageView.frame = CGRectMake(KScreenWidth/4+20, _headerView.bottom-35, KScreenWidth/2-40, 35);
    self.messageView.backgroundColor = [[UIColor blackColor] initWithWhite:0 alpha:0.7];
    self.messageView.layer.masksToBounds = YES;
    self.messageView.layer.cornerRadius = 5;


    self.messagePhoto = [[UIImageView alloc] initWithFrame:CGRectMake(30, 2.5, 30, 30)];
    self.messagePhoto.layer.masksToBounds = YES;
    self.messagePhoto.layer.cornerRadius = self.messagePhoto.height/2;
    [self.messageView addSubview:self.messagePhoto];
    
    self.messageCount = [[UILabel alloc] initWithFrame:CGRectMake(self.messagePhoto.right+5, 2.5, self.messageView.width-40, 30)];
    self.messageCount.font = FontP(16);
    self.messageCount.textColor =[UIColor whiteColor];
    [self.messageView addSubview:self.messageCount];

    UIButton *messageButton = [UIButton buttonWithType:UIButtonTypeCustom];
    messageButton.bounds = self.messageView.bounds;
    [messageButton addTarget:self action:@selector(buttonJumpClick) forControlEvents:UIControlEventTouchUpInside];
    [self.messageView addSubview:messageButton];
    
    
    [_headerView addSubview:self.messageView];
    
    
    
    self.tableView.tableHeaderView = _headerView;
    
    if (_isFriend == YES || [_herId isEqualToString:[HQHttpManager getUserId]]) {
    } else {
        UIView *view = [UIView new];
        view.frame = CGRectMake(0, 0, KScreenWidth, 40);
        UILabel *noteLabel = [UILabel new];
        noteLabel.frame = CGRectMake(0, 10, KScreenWidth, 20);
        noteLabel.text = @"非好友只能显示10条动态";
        noteLabel.textAlignment = NSTextAlignmentCenter;
        [view addSubview:noteLabel];
        self.tableView.tableFooterView = view;
    }
    [self.tableView registerClass:[SDTimeLineCell class] forCellReuseIdentifier:kTimeLineTableViewCellId];
    
    [self sendeRequestUserInfo];
    
    [self sendRequest];

}

- (void)sendeRequestUserInfo{
    
    [HcardHttpmanager getPersionalUserInfosuccess:^(id sucess) {
        
        self.userInfoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];

        _headerView.bgImg = self.userInfoModel.background;
        _headerView.name = self.userInfoModel.nickName;
        _headerView.photo = self.userInfoModel.photo;
        
 
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];

}


//    NSLog(@"跳转查看新消息");
- (void)buttonJumpClick{
    
    FriendlinNewMessageViewController *VC =[[FriendlinNewMessageViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
    NSLog(@"跳转查看新消息");

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self sendRequestFriendmessageCount];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : FontP(18)};
    self.navigationController.navigationBar.barTintColor = Colorbackground;
    [self.navigationController.navigationBar setTranslucent:NO];

    
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page = 1;
        [weakSelf sendRequest];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        page ++;
        [weakSelf sendRequest];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}



#pragma mark =============uitableViewdelegate dateSource================
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HRTimeLineModel *timeLineModel = self.dataArray[indexPath.row];
    Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
    SDTimeLineCell *cell = [tableView dequeueReusableCellWithIdentifier:kTimeLineTableViewCellId];
    if (_isFriend == YES) {
        cell.operationButton.hidden = NO;
    } else {
        cell.operationButton.hidden = YES;
    }
    cell.indexPath = indexPath;
    __weak typeof(self) weakSelf = self;
    
        [cell setMoreButtonClickedBlock:^(NSIndexPath *indexPath) {
            SDTimeLineCellModel *model = weakSelf.dataArray[indexPath.row];
            model.isOpening = !model.isOpening;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    
        [cell setDidClickCommentLabelBlock:^(NSString *commentId, CGRect rectInWindow, NSIndexPath *indexPath,NSString *username) {


            _CommentKeybord = @"1";
            
            self.chetctr.hidden = NO;
            [self.chetctr.inputTextView becomeFirstResponder];
            _labCommentId= [[UILabel alloc] init];
            _labCommentId.text =[NSString stringWithFormat:@"回复: %@ ",username];
            _CommentUserId = @"";
            _CommentUserId = commentId;
            _CommentIdStr = @"";
            _CommentIdStr = username;
            _labCommentId.enabled = NO;
            _labCommentId.backgroundColor = [UIColor whiteColor];
            _labCommentId.frame = CGRectMake(0, 0, KScreenWidth, self.chetctr.inputTextView.height);
            _selectIndexPath = indexPath;
            [self.chetctr.inputTextView addSubview:_labCommentId];
            
            
            
        }];
        
        cell.delegate = self;
    
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    
    cell.model = model;
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HRTimeLineModel *timeLineModel = self.dataArray[indexPath.row];
    Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[SDTimeLineCell class] contentViewWidth:[self cellContentViewWith]];
    
}

#pragma mark - SDTimeLineCellDelegate==========视频播放方法==========

- (void)didClickPlayButton:(NSString *)url {

    _PlayerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    _PlayerView.backgroundColor = [UIColor blackColor];
    
    CABasicAnimation *animation = nil;
    //缩放
    animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    [animation setFromValue:@0.1];//设置起始值
    [animation setToValue:@1.];//设置目标值
    [animation setDelegate:self];//代理回调
    [animation setDuration:0.3];//设置动画时间，单次动画时间
    [animation setRemovedOnCompletion:NO];
    
    //you view need to replace
    [_PlayerView.layer addAnimation:animation forKey:nil];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = _PlayerView.frame;
    [btn addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat Height = KScreenWidth/4*3;
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:HttpImgUrl(url)]];
    AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer: player];
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    playerLayer.frame = CGRectMake(0, -64, KScreenWidth, Height+64);
    playerLayer.position = self.view.center;
    
    [_PlayerView.layer addSublayer: playerLayer];
    [playerLayer setNeedsDisplay];
    
    [player play];
    
    self.player = player;
    
    _playerLayer = playerLayer;
    
    self.view.backgroundColor = [UIColor blackColor];
    __weak typeof(self) weakSelf = self;
    NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
    [noteCenter addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
                            object:nil
                             queue:nil
                        usingBlock:^(NSNotification *note) {
                            [weakSelf.player seekToTime:kCMTimeZero];
                            [weakSelf.player play];
                        }];
    [_PlayerView addSubview:btn];
    [self.view.window addSubview:_PlayerView];

}

- (void)backButtonClick{
    [_player pause];
    _player = nil;
    CABasicAnimation *animation = nil;
    //缩放
    animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    [animation setFromValue:@1.0f];//设置起始值
    [animation setToValue:@0.1f];//设置目标值
    [animation setDelegate:self];//代理回调
    [animation setDuration:0.3f];//设置动画时间，单次动画时间
    [animation setRemovedOnCompletion:NO];
    
    //you view need to replace
    [_PlayerView.layer addAnimation:animation forKey:nil];

    [UIView animateWithDuration:0.3f animations:^{

       
    } completion:^(BOOL finished) {

        [self.view.window removeFromSuperview];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _PlayerView.hidden = YES;

            [_PlayerView removeFromSuperview];
        });

    }];

    
}

#pragma mark ============发布状态 ========  代理==============
- (void)didClickButtonFrienddynamic:(NSInteger)index{

    NSLog(@"index%ld",(long)index);
    switch (index) {
        case 0:{
            Friendconversations *vc = [Friendconversations new];
            vc.conversation_Type = KConversationWords;
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 1:{
            Friendconversations *vc = [Friendconversations new];
            vc.conversation_Type = KConversationPhoto;
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:{
            
           
            [self tapClick];

        }
            break;
        case 3:{
            Friendconversations *vc = [Friendconversations new];
            vc.conversation_Type = KConversationVedio;
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
    
}
#pragma mark ===========选择拍照===========
- (void)tapClick{
    [self.actionSheetTitle showGGActionSheet];
}

-(GGActionSheet *)actionSheetTitle{
    if (!_actionSheetTitle) {
        
        _actionSheetTitle = [GGActionSheet ActionSheetWithTitleArray:@[@"拍照"] andTitleColorArray:@[[UIColor blackColor]] delegate:self];
        //取消按钮颜色设置
        _actionSheetTitle.cancelDefaultColor = [UIColor blackColor];
        //如果设置了选项颜色 当颜色数组和标题数组数量对不上时 多余标题使用选项默认颜色
        //如果设置了选项颜色 当颜色数组传空时，所有选项默认使用选项颜色
        //如果没设置选项颜色 数量对不上以及颜色数组为空时都使用默认黑色
        _actionSheetTitle.optionDefaultColor = [UIColor blackColor];
    }
    return _actionSheetTitle;
}

-(void)GGActionSheetClickWithActionSheet:(GGActionSheet *)actionSheet Index:(int)index{

    [self takePhoto];

}

#pragma mark ===============发布状态弹框方法===============
- (void)clickRightButton {
    CATransition * animation = [CATransition animation];
    
    animation.duration = 0.5;    //  时间
    
    /**  type：动画类型
     *  pageCurl       向上翻一页
     *  pageUnCurl     向下翻一页
     *  rippleEffect   水滴
     *  suckEffect     收缩
     *  cube           方块
     *  oglFlip        上下翻转
     */
//    animation.type = @"pageCurl";
    
    /**  type：页面转换类型
     *  kCATransitionFade       淡出
     *  kCATransitionMoveIn     覆盖
     *  kCATransitionReveal     底部显示
     *  kCATransitionPush       推出
     */
    animation.type = kCATransitionFade;
    
    //PS：type 更多效果请 搜索： CATransition
    
    /**  subtype：出现的方向
     *  kCATransitionFromRight       右
     *  kCATransitionFromLeft        左
     *  kCATransitionFromTop         上
     *  kCATransitionFromBottom      下
     */
    animation.subtype = kCATransitionFromRight;
    
    [self.view.window.layer addAnimation:animation forKey:nil];                   //  添加动作
    
    FrienddynamicViewController * loginTipVC = [[FrienddynamicViewController alloc]init];
    loginTipVC.delegate = self;
    self.definesPresentationContext = YES;
    UIColor *color = [UIColor blackColor];
    loginTipVC.view.backgroundColor = [color colorWithAlphaComponent:0.4];
    loginTipVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self.navigationController presentViewController:loginTipVC animated:NO completion:nil];
}
#pragma mark =============Cell代理=============
//删除状态
- (void)didClickDeleteInCell:(UITableViewCell *)cell {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定要删除这条状态吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSIndexPath *index = [self.tableView indexPathForCell:cell];
        HRTimeLineModel *timeLineModel = self.dataArray[index.row];
        Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
        [HQHttpManager delActiveWithUid:[HQHttpManager getUserId] circleId:model.circleId trystId:model.trystId successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
            if (isSuccess) {
                //            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationFade];
                
                [self.dataArray removeObject:timeLineModel];
                [self.tableView reloadData];
            }
        }];
        
    }];
    UIAlertAction *cliceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:confirAction];
    [alertVC addAction:cliceAction];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];

    
 
}

- (void)didClickIconInCell:(UITableViewCell *)cell {
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    HRTimeLineModel *timeLineModel = self.dataArray[index.row];
    Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
    HomeStrangCollionViewController *UDIVC = [[HomeStrangCollionViewController alloc] init];
    UDIVC.navigationController.navigationBar.hidden = YES;
    UDIVC.UserId = [NSString stringWithFormat:@"%ld",(long)model.uid] ;
    [self.navigationController pushViewController:UDIVC animated:YES];
}

- (void)didClickcJoinButtonInCell:(UITableViewCell *)cell {
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"如果对方同意约会会互相推送绑定的手机号，确定参加吗?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HRTimeLineModel *timeLineModel = self.dataArray[index.row];
        Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
        _trystId = model.trystId;
        _circleId = model.circleId;
        [HQHttpManager addJoinWithUid:[HQHttpManager getUserId] trystId:_trystId successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
            if (isSuccess) {
                [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"参加成功"];
                [[RCIM sharedRCIM] sendMessage:ConversationType_PRIVATE targetId:@(model.uid).stringValue content:[HRTextMessage messageWithContent:@"我有兴趣哦！" extra:@"hedadaTEexffs" uid:[HQHttpManager getUserId] trystId:@(model.trystId).stringValue type:@(model.type).stringValue] pushContent:@"tryst" pushData:nil success:^(long messageId) {
                    
                } error:^(RCErrorCode nErrorCode, long messageId) {
                    
                }];
            }
        }];
    }];
    [alert addAction:cancelAction];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}
//点击回复
- (void)didClickcCommentButtonInCell:(UITableViewCell *)cell {
    NSLog(@"...");
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    HRTimeLineModel *timeLineModel = self.dataArray[index.row];
    Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
    _selectIndexPath = index;
    _trystId = model.trystId;
    _circleId = model.circleId;
    self.chetctr.hidden = NO;
    [self.chetctr.inputTextView becomeFirstResponder];
    
    
    //    [_textField becomeFirstResponder];
    //    _currentEditingIndexthPath = [self.tableView indexPathForCell:cell];
    //    [self adjustTableViewToFitKeyboard];
    //    RCEmojiBoardView *view=[[RCEmojiBoardView alloc]initWithFrame:CGRectMake(0,self.view.frame.size.height,self.view.frame.size.width, 0)];
    //
    //    //    设置表情的协议代理方法
    //    [view enableSendButton:NO];
    //    view.delegate=self;
    
    
    //[self.view addSubview:view];
}


#pragma mark ==============网络请求=======朋友圈数据===============点赞================

- (void)didClickLikeButtonInCell:(UITableViewCell *)cell opertionStr:(NSString *)opertionStr{
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    NSLog(@"...");
    NSInteger Typeteger ;
    if ([opertionStr isEqualToString:@"赞"]) {
        Typeteger =1;
    }else{
        Typeteger = 2;
    }
    
    HRTimeLineModel *timeLineModel = self.dataArray[index.row];
    Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
    _trystId = model.trystId;
    _circleId = model.circleId;
    
    [HQHttpManager addPraiseWithUid:[HQHttpManager getUserId] circleId:_circleId trystId:_trystId type:Typeteger successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            NSString *uid = [HQHttpManager getUserId];
            NSDictionary *PraiseDic = @{@"uid":@(uid.integerValue),@"nickName":[HQHttpManager userNickName]};
            NSDictionary *active1 = (NSDictionary *)timeLineModel.active;
            NSMutableDictionary *active = active1.mutableCopy;
            NSArray *praiseList = @[];
            
            NSMutableArray *array = @[].mutableCopy;
            
            if (active[@"praiseList"] != nil) {
                praiseList = active[@"praiseList"];
                array = praiseList.mutableCopy;
            }
            


            if (Typeteger  == 1) {
                
                [array addObject:PraiseDic];
                [active setValue:array forKey:@"praiseList"];
                
                timeLineModel.active = active.mutableCopy;
            }else{

                for (NSDictionary * dic in praiseList) {
                    if ([dic[@"nickName"] isEqualToString:PraiseDic[@"nickName"]] && [dic[@"uid"] isEqualToNumber:PraiseDic[@"uid"]]) {
                        [array removeObject:dic];
                    }
                }
                [active setValue:array forKey:@"praiseList"];
                NSLog(@"%@",PraiseDic);
                
                timeLineModel.active = active.mutableCopy;
          
            }
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationNone];
            });
        }
    }];
    
    

//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
//    });
}
- (void)sendRequestFriendmessageCount{
    [HQHttpManager mfWithCount:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            _FriendmessageCount = resultDic;
            self.messageCount.text = [NSString stringWithFormat:@"%@条新消息",_FriendmessageCount[@"count"]];
            [self.messagePhoto sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_FriendmessageCount[@"photo"])] placeholderImage:[UIImage imageNamed:@"llustration"]];
            NSNumber *friendNumberCount = _FriendmessageCount[@"count"];
            NSLog(@"%@",_FriendmessageCount);
            if (friendNumberCount.integerValue != 0) {
                self.messageView.hidden = NO;
            } else {
                self.messageView.hidden = YES;
            }
            [_tableView reloadData];
        }
    }];

}

- (void)sendRequest {
    [SVProgressHUD showWithStatus:@"加载数据中..."];
    WEAKSELF
    [HQHttpManager activeListWithUid:[HQHttpManager getUserId] herId:_herId page:@(page) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        [SVProgressHUD dismiss];
        NSLog(@"朋友圈数据请求%@",resultDic);
        if (isSuccess) {
            if (page == 1) {
                [self.dataArray removeAllObjects];
            }
            NSArray *array = resultDic[@"res"];
            for (NSDictionary *dic in array) {
                HRTimeLineModel *model = [HRTimeLineModel getTimeLineModelWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            if (array.count == 0) {
                page--;
            }
            [weakSelf.tableView reloadData];
            //            if (self.dataArray.count == 0) {
            //                [self configureUI];
            //            }
        } else {
            if (resultDic) {
                // [SVProgressHUD showInfoWithStatus:resultDic[@"message"]];
            }
            page--;
        }
    }];
}

- (void)didClickFinishButton {
    page = 1;
    [self sendRequest];
}

- (void)clickFinishButton {
    page = 1;
    [self sendRequest];
}

- (CGFloat)cellContentViewWith {
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (RCChatSessionInputBarControl *)chetctr {
    if (!_chetctr) {
        _chetctr = [[RCChatSessionInputBarControl alloc] initWithFrame:CGRectMake(0, KScreenHeight-50, KScreenWidth, 50) withContainerView:self.view controlType:RCChatSessionInputBarControlDefaultType controlStyle:RC_CHAT_INPUT_BAR_STYLE_CONTAINER defaultInputType:RCChatSessionInputBarInputText];
        _chetctr.delegate=self;
        _chetctr.inputTextView.delegate = self;
        [self.view addSubview:_chetctr];
    }
    return _chetctr;
}

#pragma RCEmojiViewDelegate-------

/**
 *  didTouchEmojiView
 *
 *  @param emojiView emojiView
 *  @param sendButton    string
 */

- (void)emojiView:(RCEmojiBoardView *)emojiView didTouchSendButton:(UIButton *)sendButton {
    NSLog(@"inputTextView=%@",self.chetctr.inputTextView.text);
    [self.chetctr updateStatus:KBottomBarDefaultStatus animated:YES];
    [self.view endEditing:YES];
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.10];
    [UIView setAnimationBeginsFromCurrentState: YES];
    self.chetctr.frame = CGRectMake(self.chetctr.frame.origin.x, KScreenHeight, self.chetctr.frame.size.width, self.chetctr.frame.size.height);
    [UIView commitAnimations];
    HRTimeLineModel *timeLineModel = self.dataArray[_selectIndexPath.row];
    NSString *contentString = _chetctr.inputTextView.text;
    WEAKSELF
    [HQHttpManager addCommentWithUid:[HQHttpManager getUserId] circleId:_circleId trystId:_trystId content:_chetctr.inputTextView.text successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            NSString *uid = [HQHttpManager getUserId];
            NSDictionary *CommentDic = @{@"uid":@(uid.integerValue),@"nickName":[HQHttpManager userNickName],@"content":contentString};
            NSDictionary *active1 = (NSDictionary *)timeLineModel.active;
            NSMutableDictionary *active = active1.mutableCopy;
            NSArray *commentlist = @[];
            NSMutableArray *array = @[].mutableCopy;
            if (active[@"commentList"] != nil) {
                commentlist = active[@"commentList"];
                array = commentlist.mutableCopy;
            }
            [array addObject:CommentDic];
            [active setValue:array forKey:@"commentList"];
            timeLineModel.active = active.mutableCopy;
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_selectIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            weakSelf.chetctr.inputTextView.text = @"";
        }
    }];
    weakSelf.chetctr.inputTextView.text = @"";
}

- (void)didTouchEmojiView:(RCEmojiBoardView *)emojiView touchedEmoji:(NSString *)string {
    NSLog(@"text=%@",string);
}
- (void)emojiView:(RCEmojiBoardView *)emojiView didTouchedEmoji:(NSString *)touchedEmoji {
    NSLog(@"text=%@",touchedEmoji);

}

/**
 *  didSendButtonEvent
 *
 *  @param emojiView  emojiView
 *  @param sendButton send button
 */
- (void)didSendButtonEvent:(RCEmojiBoardView *)emojiView sendButton:(UIButton *)sendButton{
    
}

- (void)chatInputBar:(RCChatSessionInputBarControl *)chatInputBar shouldChangeFrame:(CGRect)frame {
    
    if (chatInputBar.currentBottomBarStatus == KBottomBarDefaultStatus||chatInputBar.currentBottomBarStatus == KBottomBarKeyboardStatus ||chatInputBar.currentBottomBarStatus == KBottomBarEmojiStatus) {
        
        if (chatInputBar.currentBottomBarStatus ==KBottomBarDefaultStatus) {
            self.chetctr.frame = frame ;
            
            self.chetctr.hidden = NO;
            [self.view bringSubviewToFront:self.chetctr];
            _keyboardR = self.chetctr.frame;

            if ([_CommentKeybord isEqualToString:@"1"]) {
                _labCommentId.hidden = YES;
            }
            
        }else{
            self.chetctr.frame = _keyboardR ;
            self.chetctr.hidden = NO;
            [self.view bringSubviewToFront:self.chetctr];

        }
        
        return ;
    }
    self.chetctr.frame = frame;
    [self.view bringSubviewToFront:self.chetctr];

}

- (void)presentViewController:(UIViewController *)viewController functionTag:(NSInteger)functionTag {
    
}

- (void)chatSessionInputBarControlContentSizeChanged:(CGRect)frame {
    CGRect ViewRect = self.view.frame;
    ViewRect.size.height =
    CGRectGetMinY(frame) - ViewRect.origin.y;
    [self.view setFrame:ViewRect];
    
}

- (void)textViewDidChange:(UITextView *)textView {
    //    [UIView beginAnimations:@"Animation" context:nil];
    //    [UIView setAnimationDuration:0.10];
    //    [UIView setAnimationBeginsFromCurrentState: YES];
    //    _chetctr.frame = CGRectMake(_chetctr.frame.origin.x, _y, _chetctr.frame.size.width, _chetctr.frame.size.height);
    //    [UIView commitAnimations];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    _labCommentId.alpha = 0;//开始编辑时
    return YES;
}
//评论  回复评论请求方法   输入方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    

    if ([_CommentKeybord isEqualToString:@"1"]) {
        _labCommentId.hidden = YES;
        _CommentStrList = @"1";

    }else{
        _labCommentId.hidden = NO;

    }
    
    
 
    WEAKSELF

    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        NSLog(@"text=%@",textView.text);
        NSLog(@"点击键盘确认");
        [self.chetctr updateStatus:KBottomBarDefaultStatus animated:YES];
        [self.view endEditing:YES];
        [UIView beginAnimations:@"Animation" context:nil];
        [UIView setAnimationDuration:0.10];
        [UIView setAnimationBeginsFromCurrentState: YES];
        self.chetctr.frame = CGRectMake(self.chetctr.frame.origin.x, KScreenHeight-50, self.chetctr.frame.size.width, self.chetctr.frame.size.height);
        [UIView commitAnimations];
        self.chetctr.hidden = YES;
        HRTimeLineModel *timeLineModel = self.dataArray[_selectIndexPath.row];
        NSString *contentString = _chetctr.inputTextView.text;
        
        if ([_CommentStrList isEqualToString:@"1"]) {

            Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
            _circleId = model.circleId;
            
          [HcardHttpmanager CommentreplyUid:[HQHttpManager getUserId] content:_chetctr.inputTextView.text replyId:_CommentUserId.integerValue circleId:_circleId trystId:_trystId Success:^(id result) {
              

  
              
              NSString *uid = [HQHttpManager getUserId];
              NSDictionary *CommentDic = @{@"uid":@(uid.integerValue),@"nickName":[HQHttpManager userNickName],@"content":contentString,@"toNickName":_CommentIdStr,@"replyId":_CommentUserId,@"circleId":@(_circleId)};
              
              
              NSDictionary *active1 = (NSDictionary *)timeLineModel.active;
              NSMutableDictionary *active = active1.mutableCopy;
              NSArray *commentlist = @[];
              NSMutableArray *array = @[].mutableCopy;
              if (active[@"commentList"] != nil) {
                  commentlist = active[@"commentList"];
                  array = commentlist.mutableCopy;
              }
              [array addObject:CommentDic];
              [active setValue:array forKey:@"commentList"];
              timeLineModel.active = active.mutableCopy;
          [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_selectIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
              weakSelf.chetctr.inputTextView.text = @"";

          } failure:^(NSError *error) {
              
              
              
          }];
            _CommentStrList = @"0";
            _CommentKeybord = @"0";
        }else{
            [HQHttpManager addCommentWithUid:[HQHttpManager getUserId] circleId:_circleId trystId:_trystId content:_chetctr.inputTextView.text successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                if (isSuccess) {
                    NSString *uid = [HQHttpManager getUserId];
                    NSDictionary *CommentDic = @{@"uid":@(uid.integerValue),@"nickName":[HQHttpManager userNickName],@"content":contentString};
                    NSDictionary *active1 = (NSDictionary *)timeLineModel.active;
                    NSMutableDictionary *active = active1.mutableCopy;
                    NSArray *commentlist = @[];
                    NSMutableArray *array = @[].mutableCopy;
                    if (active[@"commentList"] != nil) {
                        commentlist = active[@"commentList"];
                        array = commentlist.mutableCopy;
                    }
                    [array addObject:CommentDic];
                    [active setValue:array forKey:@"commentList"];
                    timeLineModel.active = active.mutableCopy;
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:_selectIndexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    weakSelf.chetctr.inputTextView.text = @"";
                }
            }];
            weakSelf.chetctr.inputTextView.text = @"";
            //在这里做你响应return键的代码
            return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行

        }
    }
    
    return YES;
}

- (void)inputTextView:(UITextView *)inputTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//    [_chetctr updateStatus:KBottomBarKeyboardStatus animated:YES];
}

- (void)inputTextViewDidTouchSendKey:(UITextView *)inputTextView {
    NSLog(@"text=%@",inputTextView.text);
    NSLog(@"点击键盘确认");
}

- (void)didTouchKeyboardReturnKey:(RCChatSessionInputBarControl *)inputControl text:(NSString *)text {
    //self.textview.text=text;
    
    NSLog(@"text=%@",text);
    NSLog(@"点击键盘确认");
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.chetctr updateStatus:KBottomBarDefaultStatus animated:YES];
    [self.view endEditing:YES];
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.10];
    [UIView setAnimationBeginsFromCurrentState: YES];
    self.chetctr.frame = CGRectMake(self.chetctr.frame.origin.x, KScreenWidth-50, self.chetctr.frame.size.width, self.chetctr.frame.size.height);
    self.chetctr.hidden = YES;
    [UIView commitAnimations];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _tableView) {
        [self.chetctr updateStatus:KBottomBarDefaultStatus animated:YES];
        [self.view endEditing:YES];
        [UIView beginAnimations:@"Animation" context:nil];
        [UIView setAnimationDuration:0.10];
        [UIView setAnimationBeginsFromCurrentState: YES];
        self.chetctr.frame = CGRectMake(self.chetctr.frame.origin.x, KScreenHeight-50, self.chetctr.frame.size.width, self.chetctr.frame.size.height);
        [UIView commitAnimations];
        self.chetctr.hidden = YES;
        self.chetctr.inputTextView.text = @"";

    }
}

- (void)keyboardWillShow:(NSNotification *)note{
    [self.view bringSubviewToFront:self.chetctr];
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    if (self.chetctr.frame.origin.y == KScreenHeight-50-keyboardBounds.size.height) {
        return;
    }
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.10];
    [UIView setAnimationBeginsFromCurrentState: YES];
    self.chetctr.frame = CGRectMake(self.chetctr.frame.origin.x, KScreenHeight - self.chetctr.frame.size.height - keyboardBounds.size.height-64, self.chetctr.frame.size.width, self.chetctr.frame.size.height);
    _y = self.chetctr.frame.origin.y - keyboardBounds.size.height;
    

    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note{
    if (self.view.frame.origin.y==0) {
        return;
    }
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.10];
    [UIView setAnimationBeginsFromCurrentState: YES];
    self.chetctr.frame = CGRectMake(self.chetctr.frame.origin.x, KScreenHeight-50, self.chetctr.frame.size.width, self.chetctr.frame.size.height);
    [UIView commitAnimations];
    self.chetctr.hidden = YES;

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - takePhoto

- (void)startChoosePhoto {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertController addAction:firstAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)takePhoto {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"该设备不支持拍照功能" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];

    }
    else
    {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];

    }
}

#pragma mark UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出
        UIImage* oldImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        
        
        UIImageOrientation imageOrientation = oldImage.imageOrientation;
        
        UIImage * image;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(oldImage.size);
            [oldImage drawInRect:CGRectMake(0, 0, oldImage.size.width, oldImage.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }else{
            image = oldImage;
        }
        NSData *data;
        
        if (UIImagePNGRepresentation(image) == nil){
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else{
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.jpg
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        UIImage * img = [UIImage imageWithData:data];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
        Friendconversations *vc = [Friendconversations new];
        vc.conversation_Type = KConversationPhoto;
        vc.photoType = @"1";
        vc.takedPhoto = img;
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }
    

}


@end
